package dao;

import tool.Util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BlockUserDao {
    Util util = new Util();
    Connection con = null;

    public String[] getUsers() {
        List<String> userList = new ArrayList<>();
        String sql = "SELECT name FROM user where status=0";
        Connection con = util.getConnection();
        try {
            PreparedStatement preparedStatement = con.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                String userName = resultSet.getString("name");
                userList.add(userName);
            }
            // 将列表转换为字符串数组
            String[] usersArray = new String[userList.size()];
            usersArray = userList.toArray(usersArray);
            return usersArray;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (con != null) {
                    con.close();
                }
            } catch (SQLException e) {
                System.out.println(e.getMessage());
            }
        }
    }

    public void blockUser(Object selectedItem) {
        con = util.getConnection();
        String sql = "update user set status=1 where name=?";
        try {
            PreparedStatement preparedStatement = con.prepareStatement(sql);
            preparedStatement.setString(1, (String) selectedItem);
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public boolean checkUserStatus(Object selectedItem) {
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            con = util.getConnection();
            String sql = "select * from user where name=? and status=0";
            preparedStatement = con.prepareStatement(sql);
            preparedStatement.setString(1, (String) selectedItem);
            resultSet = preparedStatement.executeQuery();
            return resultSet.next();
        } catch (SQLException e) {
            throw new RuntimeException("Error checking user status", e);
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                con.close();
            } catch (SQLException e) {
                System.out.println(e.getMessage());
            }
        }
    }
}